<template>
	<view class="materials-list">
		<!-- 顶部导航 -->
		<up-navbar :fixed="false" title="用料清单" :autoBack="true" :safeAreaInsetTop="true" leftIconColor="#fff" />

		<!-- 主体内容 -->
		<view class="materials-list__main">
			<!-- 非空数据 -->
			<view class="materials-list__has-data" v-if="PageList.length">
				<m-basic-drag class="materials-list__list" v-model:tableData="PageList" itemKey="index" :column="1"
					itemHeight="160px" height="100%">
					<template #item="{ element, index }">
						<view class="materials-list__row x-f">
							<!-- 索引 -->
							<view class="materials-list__index x-f">
								<view class="materials-list__index-box">
									<text>{{ index + 1 }}</text>
								</view>
							</view>

							<!-- 内容区 -->
							<view class="materials-list__row-content x-f">
								<view class="materials-list__card x-bc">
									<!-- 左侧信息 -->
									<view class="materials-list__card-left x-f">
										<uni-icons type="minus-filled" color="#f56c6c" size="48rpx"
											@click="deleteListData(element,index)"></uni-icons>

										<view class="materials-list__card-info">
											<view class="materials-list__card-title">
												{{ element.ProductCode }} | {{ element.ProductName }} |
												{{ element.ProductSpec }}
											</view>

											<view class="materials-list__card-sub">
												<text>父件基数：</text>
												<text>{{ element.ParentNum }}</text>
											</view>
											<view class="materials-list__card-sub">
												<text>子件用量：</text>
												<text>{{ element.SunNume }}</text>
											</view>
											<view class="materials-list__card-sub">
												<text>损耗率：</text>
												<text>{{ element.LossRatio }}</text>
											</view>
										</view>
									</view>

									<!-- 右侧操作 -->
									<view class="materials-list__card-right x-f">
										<uni-icons type="bars" color="#999" size="40rpx"
											style="margin-right: 6px;"></uni-icons>
										<uni-icons type="compose" color="#999" size="40rpx"
											@click="editCell(element,index)"></uni-icons>
									</view>
								</view>
							</view>
						</view>
					</template>
				</m-basic-drag>
			</view>

			<!-- 空状态 -->
			<view class="materials-list__empty" v-else>
				<u-empty mode="data" icon="/static/image/Img/DataEmpty.png" text="暂无用料" textColor="#999"
					class="materials-list__empty-box" />
			</view>

			<!-- 添加按钮 -->
			<view class="materials-list__add-row">
				<view class="materials-list__btn-box">
					<button @click="openAddPopup('添加用料')" class="materials-list__btn-save">
						<uni-icons type="plusempty" color="#51d0d0" size="20" />
						添加用料
					</button>
				</view>
			</view>
		</view>

		<!-- 底部操作 -->
		<view class="page__content__bottom" :style="uni.$utils.disposeSafeBottomFun()">
			<button class="content_bottom_primary_Btn page__content__bottom__btn" @click="submitBtn">
				确定
			</button>
		</view>
	</view>
</template>

<script setup lang="ts">
	import { ref, reactive, onMounted, computed } from 'vue'
	import { onLoad, onShow, onUnload } from '@dcloudio/uni-app'
	import useRequestQueue from '@/uni_modules/mc-ui/libs/http/UniversalRequestQueue';
	const { request, requestByUrl, PromiseRequestByUrl, onAllComplete, onError } = useRequestQueue();
	import { useMainStore, useUserStore, usePermissionStore, useTicketStore } from '@/store';
	const mainStore = useMainStore();
	const userStore = useUserStore();
	const permissionStore = usePermissionStore();
	const ticketStore = useTicketStore();

	import mBasicDrag from '@/st_ticket/components/m-basic-drag/m-basic-drag';
	let PageList = ref<any>([]);

	let formData = reactive<any>({});


	const createTicket_Materials = ticketStore.createTicket_Materials;
	Object.assign(formData, createTicket_Materials.formData);

	if (!uni.$utils.isEmpty(createTicket_Materials.MaterialsList)) {
		PageList.value = createTicket_Materials.MaterialsList.map((item : any, index : number) => {
			return {
				...item,
				index
			}
		})
	}



	function deleteListData(item : any, index : number) {
		PageList.value.splice(index, 1)
	}

	let editIndex = ref<any>(null);

	function editCell(data : any, index : number) {
		editIndex.value = index;
		mainStore.BaseScreenParm = {
			data,
			listenName: baseScreenListenName.value
		};
		uni.navigateTo({
			url: './materialsListCellInfo'
		});
	}
	let routes = getCurrentPages(); //当前页面栈
	const baseScreenListenName = computed(() => {
		return 'materialsList_choice_' + routes.length
	})
	// 添加用料
	function openAddPopup(str ?: string) {
		mainStore.openBaseScreen({
			allowClear: true, // 清除按钮
			cmd: 'XGD_Material', // 接口名
			titleName: str,
			listeningName: baseScreenListenName.value, // 监听器
			multiple: true, // 是否开启多选
			serverSearch: { // 查询项
				format: { // 数据映射
					displayValue: "ProductInfo", // 显示值
					hiddenValue: "ProductID", // 隐藏值
					pageIndex: "PageIndex", // 分页状态页码字段
					pageSize: "PageSize", // 分页状态每页数量字段
				},
				isLocal: false, // 是否启用本地数据
				localData: [], // 当开启本地数据时使用
				isPaging: false, //是否分页
				searchKey: 'SearchKey', //搜索关键词，应包含在param中
				disabled: { // 需要禁用的数据
					data: [formData.ProductID], // 基础数组形式
					key: "ProductID", // 禁用的对应key
				},
				choiceData: PageList.value, // 选中数据
				choiceDataKey: "ProductID", // 选中数据的key
				isTree: false, // 是否开启树型下拉
			},
			param: { // 传递参数
				SearchKey: '',
				PageIndex: 1,
				PageSize: 30
			}
		});
	}

	// 确认用料
	function submitBtn() {
		PageList.value.map((item : any, index : number) => {
			return {
				...item,
				BomID: !('BomID' in item) ? 0 : item.BomID,
				BomDeID: !('BomDeID' in item) ? 0 : item.BomDeID,
				index
			}
		});
		ticketStore.createTicket_Materials.MaterialsList = PageList.value;

		uni.$emit(createTicket_Materials.listenName, {
			titleName: '用料清单'
		})
		uni.navigateBack()
	};
	function hasChoiceData(obj : any, prop : string) {
		if (obj.hasOwnProperty(prop) && !uni.$utils.isEmpty(obj[prop])) {
			return false;
		} else {
			return true;
		}
	};

	/**
	 * 判断选中的物料是否为虚设件
	 * @param {Object} param 参数
	 */
	function getIsVirtualPieces(param : any) { // 判断选中的物料是否为虚设件
		try {

			request({
				config: {
				},
				url: 'XGD_SelectMaterial',
				method: 'POST',
				data: param,
				success(ret : any) {
					PageList.value = PageList.value.concat(ret.data.ds);
				}
			});

		} catch (e) {
			uni.$utils.layer.alert('请求异常，请稍后重试！')
			//TODO handle the exception
		}
	}

	onMounted(() => {
		uni.$on(baseScreenListenName.value, (ret : any) => {
			console.log(ret);
			switch (ret.titleName) {
				case "编辑用料":
					Object.assign(PageList.value[editIndex.value], ret.data);
					PageList.value = PageList.value.map((item : any, index : any) => {
						return {
							...item,
							index
						}
					});
					break;
				case "添加用料":
					let isFictional = false;
					// 判断是否为虚设件
					// 定义字段名和默认值的数组
					const fields = [
						{
							name: 'ParentNum',
							defaultValue: 1
						},
						{
							name: 'SunNume',
							defaultValue: 1
						},
						{
							name: 'LossRatio',
							defaultValue: 0
						}
					];
					let ProductID = [] as any,
						ParentNum = [] as any,
						BomDeID = [] as any,
						LossRatio = [] as any,
						SunNume = [] as any,
						BomID = [] as any;

					let backData = ret.data.map((item : any, index : number) => {
						// 对每一个字段进行判断和处理
						fields.forEach(field => {
							if (!(field.name in item) || item[field.name] === null || item[field.name] === undefined) {
								// 如果没有字段或字段值为 null/undefined，则增加字段并默认为指定的默认值
								item[field.name] = field.defaultValue;
							} else {
								// 如果有字段且字段有值，则判断字段是否有值，没有值则默认为指定的默认值
								if (item[field.name] === '') {
									item[field.name] = field.defaultValue;
								}
							}
						});

						console.log(item);

						if (item.hasOwnProperty('Attribute') && item.Attribute == 4) {
							console.log(11111111);
							isFictional = true;
							ProductID.push(item.ProductID);
							ParentNum.push(item.ParentNum);
							BomDeID.push(item.BomDeID || 0);
							LossRatio.push(item.LossRatio);
							SunNume.push(item.SunNume);
							BomID.push(item.BomID || 0);
						}
						return {
							...item,
							index
						};
					});
					console.log(isFictional);
					if (isFictional) {
						let obj_new = {
							ProductID: ProductID.join('~'),
							ParentNum: ParentNum.join('~'),
							BomDeID: BomDeID.join('~'),
							LossRatio: LossRatio.join('~'),
							SunNume: SunNume.join('~'),
							BomID: BomID.join('~'),
						}
						getIsVirtualPieces(obj_new)
					} else {
						PageList.value = backData
					};



					break;
				default:
					break;
			}
		});

	})

	onUnload(() => {
		uni.$off(baseScreenListenName.value)
	})
</script>

<style lang="scss">
	.materials-list {
		display: flex;
		flex-direction: column;
		height: 100vh;
		background-color: #f9f9f9;

		uni-button {
			margin: initial;
		}

		&__main {
			flex: 1;
			overflow: auto;
		}

		&__has-data {
			.materials-list__list {
				.materials-list__row {
					height: 160px; // 抽出原行内 height

					.materials-list__index {
						height: 100%;
						min-width: 60px;
						justify-content: center;

						&-box {
							width: 48rpx;
							height: 48rpx;
							background-color: #51d0d0;
							color: #fff;
							border-radius: 48rpx;
							line-height: 48rpx;
							text-align: center;
						}
					}

					&-content {
						flex: 1;
						height: 100%;
						padding: 10px 16px 10px 6px; // 原行内 padding
					}
				}
			}
		}

		&__card {
			background-color: #fff;
			height: 100%;
			width: 100%;
			padding: 6px 10px;
			border-radius: 12px;

			&-left {
				display: flex;
				align-items: center;
			}

			&-info {
				padding-left: 8px;
				color: #999;
			}

			&-title {
				color: #333;
				font-size: 16px;
				font-weight: 600;
				width: 100%;
				word-break: break-all;
				overflow: hidden;
				text-overflow: ellipsis;
				display: -webkit-box;
				-webkit-line-clamp: 2;
				-webkit-box-orient: vertical;
				margin-bottom: 4px;
			}

			&-sub {
				margin-top: 4px;
				font-size: 14px;
			}

			&-right {
				height: 100%;
				display: flex;
				align-items: center;
			}
		}

		&__icon-list {
			font-weight: 600;
			margin-right: 6px; // 抽出原行内样式
		}

		&__btn-box {
			display: flex;
			align-items: center;
			justify-content: center;
			margin: 20px 0; // 抽出原行内 margin
			min-width: 100%;

			.materials-list__btn-save {
				width: 80%;
				color: #51d0d0;
				background-color: #fff;
				border: 1px solid #51d0d0;
				border-radius: 12px;
			}
		}

		/* 复选框样式 */
		.uni-checkbox-input {
			border: 2px solid #d1d1d1 !important;
		}

		.uni-checkbox-input-checked {
			background: #51d0d0;
			color: #fff !important;
			border-color: #51d0d0 !important;
		}

		&__add-row {
			display: flex;
			align-items: center;
			justify-content: center;
			font-weight: 600;
			margin-top: 20px;
			padding-bottom: 20px;
		}

		&__empty {
			margin-top: 20px;

			&-box {
				margin: 0 auto; // 抽出原行内样式
			}
		}

		&__footer {
			display: flex;
			justify-content: flex-end;
			align-items: center;
			padding: 10px 15px;
			background-color: #fff;
			border-top: 1px solid #efefef;

			.materials-list__btn-save {
				width: 44%;
				background-color: #fff;
				color: #51d0d0;
				border: 1px solid #51d0d0;
				border-radius: 12px;
			}

			.materials-list__btn-submit {
				width: 40%;
				background-color: #51d0d0;
				color: #fff;
				border-radius: 12px;
			}
		}
	}
</style>